package com.lixinlei.meetingfilm.user.controller;

import com.lixinlei.meetingfilm.user.controller.vo.LoginReqVO;
import com.lixinlei.meetingfilm.user.service.UserServiceAPI;
import com.lixinlei.meetingfilm.utils.common.vo.BaseResponseVO;
import com.lixinlei.meetingfilm.utils.exception.CommonServiceException;
import com.lixinlei.meetingfilm.utils.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserServiceAPI serviceAPI;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public BaseResponseVO login(@RequestBody LoginReqVO reqVO) throws CommonServiceException {

        // 入参校验，不能为空
        reqVO.checkParam();

        // 验证用户名和密码是否正确
        String userId = serviceAPI.checkUserLogin(reqVO.getUsername(), reqVO.getPassword());

        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        // randomKey 是用来签名做盐的
        String randomKey = jwtTokenUtil.getRandomKey();
        /**
         * token 中有 4 项内容：
         * createTime
         * expireTime
         * randomKey - JWT数据签名： AES -> 源数据 + 盐 -> 服务端在 token 中解析出 randomkey -> 数据验签
         * userId
         */
        String token = jwtTokenUtil.generateToken(userId, randomKey);

        Map<String,String> result = new HashMap<>();
        result.put("randomKey", randomKey);
        result.put("token", token);

        return BaseResponseVO.success(result);
    }

}
